package cn.faifai.desktop.view.components;

import cn.faifai.desktop.api.FileUrlController;
import cn.faifai.desktop.api.TagController;
import cn.faifai.desktop.events.FileSecondaryClickEvent;
import cn.faifai.desktop.events.TagClearEvent;
import cn.faifai.desktop.events.TagNodeIsSelectedEvent;
import cn.faifai.desktop.events.TreeNodeIsSelectedEvent;
import cn.faifai.desktop.view.components.menus.FileListMenu;
import cn.faifai.framework.utils.SingleEvenBus;
import cn.faifai.tagapi.dto.SubDirectoryDto;
import cn.faifai.tagapi.dto.TagSerialize;
import cn.faifai.tagapi.entity.IFile;
import com.google.common.eventbus.Subscribe;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.ListView;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashSet;

@Component
@Slf4j
public class FileDetail extends VBox {

    // 创建一个ListView实例
    private ListView<String> listView;
    private ObservableList<String> files;
    private Long selectedTagId;
    private String selectedFilePath;

    @Autowired
    FileUrlController fileUrlController;
    @Autowired
    TagController tagController;

    public FileDetail()
    {
        log.info("构造文件详情对象");
    }

    public FileDetail initUI()
    {
        log.info("初始化文件详情");
        listView = new ListView<>();

        // 创建一个ObservableList并添加一些示例数据
        files = FXCollections.observableArrayList(
                "Java",
                "JavaFX",
                "Spring",
                "Hibernate",
                "Maven"
        );

        // 将数据设置到ListView中
        listView.setItems(files);

        // 设置选择模式（可选）
        listView.getSelectionModel().setSelectionMode(javafx.scene.control.SelectionMode.SINGLE);

        // 设置鼠标点击事件监听器，当用户右击时显示ContextMenu
        listView.setOnMouseClicked(event -> {
            if (event.getClickCount() == 2) { // 检查是否是双击
                log.info("双击事件");
                FileListMenu.getMenu().hide();
                String selectedItem = listView.getSelectionModel().getSelectedItem();
                fileUrlController.openFile(selectedItem);
            }
            if (event.getButton() == MouseButton.SECONDARY) { // 检查是否是右键点击
                FileListMenu.getMenu().hide();
                FileListMenu.getMenu().show(listView, event.getScreenX(), event.getScreenY());

                // 选中被右键点击的项
                String selectedItem = listView.getSelectionModel().getSelectedItem();
                SingleEvenBus.getInstance().post(new FileSecondaryClickEvent(0l,selectedItem));
            } else {
                FileListMenu.getMenu().hide(); // 隐藏ContextMenu
            }
        });

        listView.setMaxWidth(Double.MAX_VALUE);
        listView.setMaxHeight(Double.MAX_VALUE);

        this.getChildren().add(listView);
        // 这个是可以确定是根据某个对象实例关联的，所以如果有listView1和listView2，且只设置listView1，listView2是不受影响的
        VBox.setVgrow(listView, Priority.ALWAYS);

        return this;
    }

    @Subscribe
    public void onTreeNodeIsSelectedEvent(TreeNodeIsSelectedEvent event)
    {
        selectedFilePath = event.getNodeKey();
        log.info("收到文件详情查询需求");
        String path = event.getNodeKey();
        log.info("收到地址：{}", path);
        SubDirectoryDto subPath;
        try {
            subPath = fileUrlController.getSubPath2(path);
        }catch (Exception e){
            log.error("获取文件失败", e);
            subPath = new SubDirectoryDto(new ArrayList<>(), new ArrayList<>());
        }
        files.clear();
        files.addAll(subPath.getFiles());
        if (files.isEmpty()) files.addAll("无法识别为目录或者该目录下无文件", "如果您确定选中项是目录，请通过左侧目录树查询子目录");
        listView.setItems(files);
    }

    @Subscribe
    public void onTagNodeIsSelectedEvent(TagNodeIsSelectedEvent event)
    {
        selectedTagId = event.getId();
        log.info("标签选中事件");
        TagSerialize tag;
        try {
            tag = tagController.getTagById(event.getId());
        }catch (Exception e){
            log.error("获取文件失败", e);
            tag = new TagSerialize();
            tag.setIFiles(new HashSet<>());
        }
        files.clear();
        files.addAll(tag.getIFiles().stream().map(IFile::getPath).toList());
        if (files.isEmpty()) files.add("选中标签没有关联文件");
        listView.setItems(files);
    }

    @Subscribe
    public void handleTagClearEvent(TagClearEvent event) {
        log.info("标签清除事件");
        TagSerialize tag;
        try {
            tag = tagController.getTagById(selectedTagId);
        }catch (Exception e){
            log.error("获取文件失败", e);
            tag = new TagSerialize();
            tag.setIFiles(new HashSet<>());
        }
        files.clear();
        files.addAll(tag.getIFiles().stream().map(IFile::getPath).toList());
        if (files.isEmpty()) files.add("选中标签没有关联文件");
        listView.setItems(files);
    }
}
